package block

import (
	"bytes"
	"github.com/boltdb/bolt"
)

/**
 * @author: 清秋
 * @email: 15770670622
 * @datetime: 13:50 2022/3/16
 * @Description:
 */

type ChainIterator struct {
	//数据库，要从数据库中读取区块
	DB *bolt.DB
	//标志位，表示当前到哪一个区块
	currentHash []byte
}

//获取数据库中的区块信息
func (iterator *ChainIterator) Next() (*Block, error) {
	var block *Block
	var err error
	err = iterator.DB.View(func(tx *bolt.Tx) error {

		//找桶
		bk := tx.Bucket([]byte(BUCKET_BLOCK))
		blockBytes := bk.Get(iterator.currentHash)
		//使用反序列化来找对应[]byte的结构体
		block, err = DeSerialize(blockBytes)
	if err != nil {
		return err
	}
		iterator.currentHash = block.PrevHash
		return nil
	})
	return block, err
}

//判断是否还有上一个区块
func (iterator *ChainIterator) HasNext() bool {

	int := bytes.Compare(iterator.currentHash, nil)

	return int != 0
}
